<?php

class AppController extends Controller{
    
    var $uses = array(
        'User', 'Sport', 'Trick', 'ModulesSport','Module'
    );
    
    var $components = array(
        'Auth' => array(
 
            'authError' => 'Did you really think you are allowed to see that?',
            'authenticate' => array(
                'Form' => array(
                    'fields' => array('username' => 'email')
                )
            ),
            'authorize' => array(
            )
        ),
        'Session',
        'RequestHandler'
    );
    
    var $helpers = array('Session', 'Date', 'Html','Form', 'Display', 'Js');
    
    public function getCurrentUserId(){
        return $this->Auth->user('id');
    }
    
    public function getCurrentUser(){
        $user = $this->User->getUser('first', array(
            'conditions' => array(
                'User.id' => $this->getCurrentUserId()
            ),
            
        ));
               
        if (isset($user['User']['password']))
            unset($user['User']['password']);
        return $user;
    }
    
    public function getCurrentSport(){
        return $this->Session->read('currentSport');
    }
    
    
    function isAuthorized($user) {        
        return true;
    }
    
    
    
    
    /**
     *  Appelé si l'on essaye de consulter un utilisateur qui n'existe pas.
     * @return type 
     */
    public function unknownUser(){
        $this->Session->setFlash("Unknown User");
        return 1;
    }
      
    public function beforeRender(){
        /**
         * Utilisateur courant
         */
        if ($this->getCurrentUserId()){
             $this->set('isUserConnected', true);
             $this->set('currentUser', $this->getCurrentUser());
        }
        else{
             $this->set('isUserConnected', false);
        }
        
        /**
         * Sport courant (ou null)
         */
        $sport = $this->getCurrentSport();
        $this->set('currentSport', $sport);
        
        debug($this->getCurrentSportId());
    }
    
    public function afterRender(){        
        
    }
    
    public function beforeFilter() {
        parent::beforeFilter();
        
        if ($this->RequestHandler->isAjax()){
            $this->layout = null;
        }
        else{
            $action = $this->request->params['action'];
            if (substr($action, 0, 6) == 'admin_'){
                $this->layout = 'admin';
            }
        }
        
        
    }
    
    /**
     *  Change le sport courrant a celui passé en paramètre. 
     *  Si le sport est le même on ne change rien.
     * @param type $sportId 
     */
    public function changeCurrentSport($sportId, $redirect= true){
        
        if ($this->getCurrentSportId() != $sportId){
            $sport = $this->Sport->find('first', array(
                'conditions' => array(
                    'Sport.id' => $sportId
                )
            ));

            $this->Session->write('currentSport', $sport);
            $this->Session->write('currentSportId', $sportId);
            
        }
        if ($redirect){
            $this->redirect($this->referer());            
        }
        else{
            return true;
        }
    }
    
    public function getCurrentSportId(){
        return $this->Session->read('currentSportId');
    }
     
    /**
     *  Génère la liste des tricks sous la forme
     *  -- Sport
     *      => Spin 
     *          => 180,
     *          => 360
     *      => Cork 
     *          => Cork 360,
     *          => Cork 540 
     *          ...
     *          => Triple cork 1440
     * 
     * @param int $sportId
     * @param array $conditions
     */
    public function getListTricks($sportId, $conditions = array()){
        $this->Trick->TricksTypesSpin->hasMany['Trick']['conditions'] = array(
            'Trick.sports_id' => $sportId
        );
        $tricks = $this->Trick->TricksTypesSpin->find('all', array(
            'order' => array('TricksType.name', 'TricksType.multiple', 'TricksTypesSpin.spin'),
            'fields' => array('TricksTypesSpin.*', 'TricksType.*'),
            'conditions' => $conditions
        ));
        
        $oldTrickName = null;
        
        $options = array();
        foreach ($tricks as $trick){
            // Evite de planter le code si les contraintes d'intégrité de la table ne sont pas respercté !
            if (!empty($trick['Trick'][0])){
                
                if ($oldTrickName != $trick['TricksType']['name']){
                    $oldTrickName = $trick['TricksType']['name'];
                    $options[$oldTrickName] = array();
                    $oldTrickMultiple = null;
                }
                if ($oldTrickMultiple != $trick['TricksType']['multiple']){
                    $oldTrickMultiple = $trick['TricksType']['multiple'];
                    $options[$oldTrickName][$oldTrickMultiple] = array();
                }
                
                $trick['Trick'] = $trick['Trick'][0];
                $options[$oldTrickName][$oldTrickMultiple][$trick['Trick']['id']] = array(
                    //'name' => $trick['TricksType']['name'],
                    //'multiple' => $trick['TricksType']['multiple'],
                    'spin' => $trick['TricksTypesSpin']['spin'],
                    'name' => $trick['Trick']['name']
                );
                
            }
        }
        
        //debug($options);
        
        // Création des options 
        
        return $options;
    }
    
    
    /**
     *  Retourne les modules d'un sport
     * @param Int $sportId
     * @param array $options 
     */
    public function getListModules($sportId, $options = array()){
        $data = $this->ModulesSport->find('list', array(
            'conditions' => array(
                'ModulesSport.sports_id' => $sportId
            ),
            'fields' => array(
                'ModulesSport.modules_id', 
                'ModulesSport.id'
            ),
            'recursive' => -1
        ));
        $conditions = array();
        $conditions['OR'] = array();
        foreach ($data as $moduleSportId => $moduleId){
            $conditions['OR'][] = ' Module.id = '.$moduleSportId;
        }
        $tree = $this->Module->generateTreeList(array(
            $conditions,
        ));
        
        $result = array();
        foreach ($tree as $moduleId => $val){
            $result[$data[$moduleId]] = $val;
        }
        
        return $tree;
    }
    
    

    /**
     * Retourne le dossier dans lequel les vidéos des utilisateurs sont enregistré
     */
    public function getVideoFolder(){
        return APP . 'webroot/video';
    }
        
}


?>
